#include "bbh_thread.h"

#include "bbh_outbuffer.h"

int bbh_thread_create(bbh_thread_t**ppobj)
{
    bbh_thread_t*p = (bbh_thread_t*)malloc(sizeof(bbh_thread_t));
    if (NULL == p) {
        return -1;
    }
    memset(p, 0, sizeof(bbh_thread_t));

    bbh_outbuffer_create(4096, &p->msg_buf);

    //p->msg_buf.max_len = 4096;// yueqq
    *ppobj = p;
    return 0;
}

bbh_thread_t* bbh_thread_tsd(pthread_key_t thd_key)
{
    int r;
    bbh_thread_t* p = (bbh_thread_t*) pthread_getspecific(thd_key);
    if (NULL == p) {
        r = bbh_thread_create(&p);
        if (r < 0) {
            return NULL;
        }
        r = pthread_setspecific(thd_key, p);
        if (r < 0) {
            bbh_thread_free(p);
            return NULL;
        }
    }
    bbh_outbuffer_reset(p->msg_buf);
    return p;
}


void bbh_thread_free(void*_)
{
    bbh_thread_t*thd = (bbh_thread_t*)_;
    bbh_outbuffer_free(thd->msg_buf);
    free(_);
}
